package com.xgr.wonderful.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.util.EasyUtils;
import com.google.gson.Gson;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.xgr.wonderful.activity.base.BaseActivity;
import com.xgr.wonderful.adapter.ChatMsgAdapter;
import com.xgr.wonderful.constant.Constant;
import com.xgr.wonderful.constant.HttpGetUrl;
import com.xgr.wonderful.db.DatabaseUtil;
import com.xgr.wonderful.entity.Status;
import com.xgr.wonderful.entity.SuperConversation;
import com.xgr.wonderful.entity.User;
import com.xgr.wonderful.utils.Cache;
import com.xgr.wonderful.utils.HXUtils;
import com.xgr.wonderful.utils.HttpProxy;
import com.xgr.wonderful.utils.LogUtils;
import com.xgr.wonderful.utils.ToastFactory;
import com.xgr.wonderful.utils.HttpProxy.IHttpRequestListener;
import com.xgr.wonderful.R;

/**
 *1. conversationActivity跳转过来，这个时候肯定已经有remoteUser对象了
 *2. 从PersonalActivity中跳转过来， 也一定有remoteUser对象 
 * 传递进来的应该是User对象 
 * 一定要有两个参数 ：username/id ,photo
 * @author lsj
 *
 */
public class ChatActivity extends BaseActivity {
	private ListView mListView;
	private Button mSendBtn;
	private EditText mMsgInput;
	private ProgressBar mProgressBar;
	private ActionBar actionbar;

	private NewMsgBroadcastRecevier receiver;
	//private NotificationManager mNotificationManager;
	private Notification notification ;

	private ChatMsgAdapter mChatMsgAdapter;
	private User remoterUser;
	private EMConversation mConversation;

	private boolean isloading = false;
	private boolean haveMoreData = true;
	private final int pagesize = 20;
	
	private HttpProxy httpProxy ;

	@Override
	protected void onCreate(Bundle bundle) {
		// TODO Auto-generated method stub
		super.onCreate(bundle);
		//adjust_pan:当前窗口的内容将自动移动以便当前焦点从不被键盘覆盖和用户能总是看到输入内容的部分
		//state_always_hidden:当该Activity主窗口获取焦点时，软键盘也总是被隐藏的
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		setContentView(R.layout.activity_chat);
		notificationManager.cancel(Constant.NEW_MESSAGE_NOTIFICATION_ID) ;
		
		remoterUser = (User) getIntent().getSerializableExtra("data" );
		
		mConversation = EMChatManager.getInstance().getConversation(
				remoterUser.getID().toString());
		mConversation.resetUnreadMsgCount();//恢复

		actionbar = (ActionBar) findViewById(R.id.actionbar_chat);
		//说明此时对方的信息已经 从服务 器拉取到
		actionbar.setTitle(remoterUser.getUsername()+"") ;
		actionbar.setDisplayHomeAsUpEnabled(true);
		// 设置actionbar的左边按钮的单击事件监听
		actionbar.setHomeAction(new Action() {
			@Override
			public void performAction(View view) {
				// TODO Auto-generated method stub
				finish();
			}
			@Override
			public int getDrawable() {
				// TODO Auto-generated method stub
				return R.drawable.weix_logo_blank;
			}
		});
		mListView = (ListView) findViewById(R.id.chat_msg_list);
		mMsgInput = (EditText) findViewById(R.id.chat_msg_input);
		mSendBtn = (Button) findViewById(R.id.chat_msg_send);
		mProgressBar = (ProgressBar) findViewById(R.id.chat_msg_loadmore);
		mProgressBar.setVisibility(View.GONE);
		mSendBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				sendText(mMsgInput.getText().toString().trim());
			}
		});
		//可以用来 改变背景
		mMsgInput.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus){
					LogUtils.i(TAG, "edittext has focus") ;
				}else {
					LogUtils.i(TAG, "edittext has no focus") ;
				}
			}
		}) ;
		//可以用来改变 button上面 的字，如果有文字输入时，和没有文字输入时
		mMsgInput.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if (TextUtils.isEmpty(s)){
					
				}else {
					
				}
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
			
			}
		}) ;
		mListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				hideSoftInput() ;
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					if (view.getFirstVisiblePosition() == 0 && !isloading
							&& haveMoreData) {
						isloading = true;
						mProgressBar.setVisibility(View.VISIBLE);
						// sdk初始化加载的聊天记录为20条，到顶时去db里获取更多
						List<EMMessage> messages;
						try {
							messages = mConversation.loadMoreMsgFromDB(
									mChatMsgAdapter.getItem(0).getMsgId(),
									pagesize);
						} catch (Exception e) {
							e.printStackTrace();
							mProgressBar.setVisibility(View.GONE);
							return;
						}
						try {
							Thread.sleep(300);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						if (messages.size() != 0) {
							mChatMsgAdapter.notifyDataSetChanged();
							mListView.setSelection(messages.size() - 1);
							if (messages.size() < pagesize) {
								haveMoreData = false;
							}
						} else {
							haveMoreData = false;
						}
						mProgressBar.setVisibility(View.GONE);
						isloading = false;
					}
					break;

				default:
					break;
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
			}
		});

		mChatMsgAdapter = new ChatMsgAdapter(mContext, remoterUser);
		mListView.setAdapter(mChatMsgAdapter);
		//注册各种广播 
		receiver = new NewMsgBroadcastRecevier();
		HXUtils.EMRegisterReceiver(ChatActivity.this, receiver,
				Constant.NEW_MESSAGE_PRIORITY_HIGH);
		HXUtils.EMRegisterReceiver(ChatActivity.this, ackMessageReceiver, 
				Constant.NEW_MESSAGE_PRIORITY_HIGH) ;
		HXUtils.EMRegisterReceiver(ChatActivity.this, deliveryAckMessageReceiver, 
				Constant.NEW_MESSAGE_PRIORITY_HIGH) ;
		
		int count = mListView.getCount();
		if (count > 0) {
			mListView.setSelection(count - 1);
		}
	}

	private void hideSoftInput (){
		InputMethodManager imm = (InputMethodManager)
				getSystemService(Context.INPUT_METHOD_SERVICE) ;
		imm.hideSoftInputFromWindow(mMsgInput.getWindowToken(), 0) ;
	}
	
	private void sendText(String content) {
		if (content.length() > 0) {  
			EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
			TextMessageBody txtBody = new TextMessageBody(content);
			message.addBody(txtBody);
			message.setReceipt(remoterUser.getID().toString());
			mConversation.addMessage(message);
			// 通知adapter消息有变,adapter会根据加入的这条message显示消息和调用sdk的发送方法
			mChatMsgAdapter.notifyDataSetChanged();
			mListView.setSelection(mListView.getCount() - 1);
			mMsgInput.setText("");
		}else {
			ToastFactory.getToast(mContext, "请输入内容").show() ;
		}
	}
	/**
	 * 不是发给当前会话和评论的情况下，会的notification提示
	 * @author lsj
	 *
	 */
	private class NewMsgBroadcastRecevier extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {

			abortBroadcast();
			String username = intent.getStringExtra("from");
			String msgid = intent.getStringExtra("msgid");
			EMMessage message = EMChatManager.getInstance().getMessage(msgid);
			// 如果是评论推送，则直接返回，从而让mainactivity的receiver去处理这个消息
			if (message.getBooleanAttribute(Constant.COMMENT_PUSH_BY_HX, false) == true) {
				LogUtils.i(TAG, "new comment");
				notifyNewMessage(message);//通知评论
				return;
			}
			// 消息不是发给当前会话
			if (!username.equals(remoterUser.getID().toString())) {
				LogUtils.i(TAG, "not current chat");
				notifyNewMessage(message);
				return;
			}
			//是发给当前会话的
			LogUtils.i(TAG, "refresh current chat");
			mChatMsgAdapter.notifyDataSetChanged();
			mListView.setSelection(mListView.getCount() - 1);
		}
	}
	/**
	 * 消息回执BroadcastReceiver
	 */
	private BroadcastReceiver ackMessageReceiver = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			abortBroadcast() ;
			String msgid = intent.getStringExtra("msgid") ;
			String from = intent.getStringExtra("from") ;
			EMConversation conversation = EMChatManager.getInstance().getConversation("from");
			if (conversation!= null){
				//把message设为已读
				EMMessage msg = conversation.getMessage(msgid );
				if (msg!= null){
					//是否应该是只当消息是发给当前 时？
					msg.isAcked = true ;
				}
			}
			mChatMsgAdapter.notifyDataSetChanged() ;
		}
		
	} ;
	/**
	 * 消息送达BroadcastReceiver
	 */
	private BroadcastReceiver deliveryAckMessageReceiver = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			abortBroadcast() ;
			String msgid = intent.getStringExtra("msgid");
			String from = intent.getStringExtra("from");
			EMConversation  conversation= EMChatManager.getInstance().getConversation(from);
			if (conversation!= null){
				EMMessage msg = conversation.getMessage(msgid);
				if (msg!= null){
					msg.isDelivered = true ;
				}
			}
		}
		
	};


	// 消息不是当前 会话时调用的
	private void notifyNewMessage(EMMessage message){
		if (!EasyUtils.isAppRunningForeground(this)){
			LogUtils.i(TAG, "app running forground") ;
			return ;
		}
		LogUtils.i(TAG, "notify");
		
		if (notification== null){
			notification = new Notification();
			notification.icon = R.drawable.weix_logo_blank ;
			notification.flags= Notification.FLAG_AUTO_CANCEL ;
		}
		if (notificationManager == null) {
			notificationManager = (NotificationManager) getSystemService(
					Context.NOTIFICATION_SERVICE);
		}
		String from = message.getFrom() ;//这里的from是userid
		String msgid = message.getMsgId() ;
		// 如果是评论推送，则直接返回，从而让mainactivity的receiver去处理这个消息
		if (message.getBooleanAttribute(Constant.COMMENT_PUSH_BY_HX, false) == true) {
			//评论提醒 
			String pushStatusJson = ((TextMessageBody)message.getBody()).getMessage();
			String fromUsername = message.getStringAttribute(Constant.COMMENT_PUSH_FROM, "") ;
			LogUtils.i(TAG, "status:"+ pushStatusJson) ;
			//Cache.putCommentReceivedStatus(pushStatusJson) ;
			Status pushStatus  = null;
			try {
				pushStatus = new Gson().fromJson(pushStatusJson, Status.class) ;
				List< Status> commentReceivedStatus = Cache.getCommentRecevicedStatus() ;
				if (commentReceivedStatus!= null && commentReceivedStatus.size()!= 0){
					//已经 存在收到的评论,则要更新一下数据 
					for (Status temp : commentReceivedStatus){
						if (String.valueOf(temp.getId()).equals(String.valueOf(pushStatus.getId()))){
							commentReceivedStatus.remove(temp) ;
						}
					}
				}else {
					commentReceivedStatus = new ArrayList<Status>() ;
				}
			    commentReceivedStatus.add(pushStatus) ;
			    //保存下来
				Cache.putCommentReceivedStatus(new Gson().toJson(commentReceivedStatus)) ;
			} catch (Exception e) {}
			//intent.putExtra("data", pushStatus);//
			Intent intent = new Intent(this ,CommentReceivedActivity.class) ;
			PendingIntent pendingIntent = PendingIntent.getActivity(this , 
					Constant.NEW_COMMENT_NOTIFICATION_ID, intent, Intent.FLAG_ACTIVITY_NEW_TASK) ;
			notification.tickerText= "收到来自"+fromUsername+"的评论";
			notification.setLatestEventInfo(this, "微圈", "收到来自"+fromUsername+"的评论",pendingIntent);
			notificationManager.notify(Constant.NEW_COMMENT_NOTIFICATION_ID,
					notification);
			//如果是评论，要删除这条消息,以免在聊天里面显示
			EMChatManager.getInstance().getConversation(from).removeMessage(msgid) ;
		}else { //新会话收到消息和当前会话收到消息两种,如果是当前会话收到消息，则不用提示
			if (String.valueOf(remoterUser.getID()).equals(from)){
				return ;
			}
			//不是当前会话，要进行提示，并要查看数据库中是否有remoteUser信息，如果 没有，要进行查询。
			if (DatabaseUtil.getInstance().getConversation(Integer.valueOf(from))== null){
				String url = HttpGetUrl.GetUser() + "?id="+ from.toString();
				httpProxy = new HttpProxy() ;
				httpProxy.queryUserByUserID(url, new IHttpRequestListener() {
					
					@Override
					public void OnHttpRequestSuccessful(String result, int errCode) {
						if (errCode == Constant.ERR_HTTP_REQUEST_SUCCESS){
							User remoteUser = null ;
							try {
								remoteUser = new Gson().fromJson(result, User.class);
							} catch (Exception e) {}
							if (remoteUser!= null && remoteUser.getUsername()!= null){
								//下面这句应该可以不加，不清楚
								LogUtils.i(TAG, "new conversation msg push and get user info ok") ;
								DatabaseUtil.getInstance().initConversationDao(getApplicationContext()) ;
								SuperConversation superConversation = new SuperConversation(
										remoteUser.getID(), remoteUser.getUsername(),
										remoteUser.getPhoto());
								DatabaseUtil.getInstance().addConversation(
										remoteUser.getID(), superConversation);
							}
						}
					}
					@Override
					public void OnHttpRequestStart() {
					
					}	
					@Override
					public void OnHttpRequestFailure(String info) {
					}
				}) ;
			}
			//上面的查询过程，是单独在一个线程进行的
			Intent intent1 = new Intent(this, ConversationActivity.class );
			PendingIntent pendingIntent = PendingIntent.getActivity(this , 
					Constant.NEW_MESSAGE_NOTIFICATION_ID, intent1, Intent.FLAG_ACTIVITY_NEW_TASK) ;
			notification.tickerText= "收到了新的消息";
			notification.setLatestEventInfo(this, "微圈", "收到了新消息",pendingIntent);
			notificationManager.notify(Constant.NEW_MESSAGE_NOTIFICATION_ID,
					notification);
		}
		
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		if (receiver != null) {
			try {
				unregisterReceiver(receiver);
				receiver = null;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			unregisterReceiver(ackMessageReceiver) ;
			ackMessageReceiver = null ;
			unregisterReceiver(deliveryAckMessageReceiver) ;
			deliveryAckMessageReceiver = null ;
		} catch (Exception e) {
			// TODO: handle exception
		}
		super.onDestroy();
	}

	
	
}
